package com.assessment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.assessment.entity.*;
import com.assessment.mapper.AitemavgMapper;
import com.assessment.mapper.ApeoMapper;
import com.assessment.mapper.AscoreMapper;
import com.assessment.service.AitemavgService;
import com.assessment.service.AscoreService;
import com.assessment.vo.NoScoreVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.assessment.utils.Constant.SUBMIT;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 鑫十一
 * @since 2021-12-15
 */
@Service
@Transactional
public class AscoreServiceImpl extends ServiceImpl<AscoreMapper, Ascore> implements AscoreService {
    private static final Logger log1 = LoggerFactory.getLogger(AscoreServiceImpl.class);
    @Autowired(required = false)
    private AitemavgMapper aitemavgMapper;

    @Autowired(required = false)
    private ApeoMapper apeoMapper;

    @Override
    public List<Column> getColumns() {
        List<Column> columns = new ArrayList<>();
        columns.add(new Column().setLabel("考核").setProp("aname"));
        columns.add(new Column().setLabel("考核项").setProp("itname"));
        columns.add(new Column().setLabel("考核对象").setProp("bpname"));
        columns.add(new Column().setLabel("评分人").setProp("apname"));
        columns.add(new Column().setLabel("分数").setProp("score"));
        columns.add(new Column().setLabel("状态").setProp("status"));
        return columns;
    }


    @Override
    public List<Column> getNoScoreColumns() {
        List<Column> columns = new ArrayList<>();
        columns.add(new Column().setLabel("部门").setProp("dname"));
        columns.add(new Column().setLabel("人员").setProp("pname"));
        return columns;
    }

    @Override
    public List<Column> getNumColumns() {
        List<Column> columns = new ArrayList<>();
        columns.add(new Column().setLabel("考核对象").setProp("name"));
        columns.add(new Column().setLabel("自评").setProp("self"));
        columns.add(new Column().setLabel("互评").setProp("diff"));
        columns.add(new Column().setLabel("服务对象").setProp("service"));
        columns.add(new Column().setLabel("校领导").setProp("leader"));
        return columns;
    }
    @Override
    public List<Column> getABCDColumns() {
        List<Column> columns = new ArrayList<>();
        columns.add(new Column().setLabel("考核对象").setProp("name"));
        columns.add(new Column().setLabel("自评(A)").setProp("selfA"));
        columns.add(new Column().setLabel("自评(B)").setProp("selfB"));
        columns.add(new Column().setLabel("自评(C)").setProp("selfC"));
        columns.add(new Column().setLabel("自评(D)").setProp("selfD"));
        columns.add(new Column().setLabel("互评(A)").setProp("diffA"));
        columns.add(new Column().setLabel("互评(B)").setProp("diffB"));
        columns.add(new Column().setLabel("互评(C)").setProp("diffC"));
        columns.add(new Column().setLabel("互评(D)").setProp("diffD"));
        columns.add(new Column().setLabel("服务对象(A)").setProp("serviceA"));
        columns.add(new Column().setLabel("服务对象(B)").setProp("serviceB"));
        columns.add(new Column().setLabel("服务对象(C)").setProp("serviceC"));
        columns.add(new Column().setLabel("服务对象(D)").setProp("serviceD"));
        columns.add(new Column().setLabel("校领导(A)").setProp("leaderA"));
        columns.add(new Column().setLabel("校领导(B)").setProp("leaderB"));
        columns.add(new Column().setLabel("校领导(C)").setProp("leaderC"));
        columns.add(new Column().setLabel("校领导(D)").setProp("leaderD"));
        return columns;
    }

    private Integer getItemSum(String bpid, String[] strings, Boolean withSubmit){
        QueryWrapper<Ascore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bpid", bpid);
        queryWrapper.in("itid", strings);
        if (withSubmit){
            queryWrapper.eq("status", SUBMIT);
        }
        return this.count(queryWrapper);
    }

    @Override
    public Integer getABCDSum(String bpid, String[] strings, String score){
        QueryWrapper<Ascore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bpid", bpid);
        queryWrapper.in("itid", strings);
        queryWrapper.eq("status", SUBMIT);
        queryWrapper.eq("score", score);
        return this.count(queryWrapper);
    }

    @Override
    public List<AScoreNum> getNumlist(String pname) {
        List<AScoreNum> aScoreNums = new ArrayList<>();
        // 获取列表
        QueryWrapper<Ascore> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("Distinct bpid, bpname");
        List<Ascore> list = this.list(queryWrapper);
        list.forEach(ascore -> {
            if (pname.equals("") || ascore.getBpname().equals(pname)){
                // 获取每一项自评的总人数
                log1.info(String.valueOf(ascore));
                Integer selfSum = getItemSum(ascore.getBpid(), new String[]{"1477556092805337089", "1477561398275952642"},false);
                // 获取每一项参加自评的人数
                Integer selfSubmitSum = getItemSum(ascore.getBpid(), new String[]{"1477556092805337089", "1477561398275952642"},true);
                // 获取每一项互评的总人数
                Integer diffSum = getItemSum(ascore.getBpid(), new String[]{"1477561726815784961", "1477561857279610881"},false);
                // 获取每一项参加互评的人数
                Integer diffSubmitSum = getItemSum(ascore.getBpid(), new String[]{"1477561726815784961", "1477561857279610881"},true);
                // 获取每一项服务对象的总人数
                Integer serviceSum = getItemSum(ascore.getBpid(), new String[]{"1477562158057345026", "1477562403365408770", "1477562805473333249", "1477562999044657153"},false);
                // 获取每一项服务对象的人数
                Integer serviceSubmitSum = getItemSum(ascore.getBpid(), new String[]{"1477562158057345026", "1477562403365408770", "1477562805473333249", "1477562999044657153"},true);
                // 获取每一项服务对象的总人数
                Integer leaderSum = getItemSum(ascore.getBpid(), new String[]{"1481495165907509250", "1481495305896599553"},false);
                // 获取每一项服务对象的人数
                Integer leaderSubmitSum = getItemSum(ascore.getBpid(), new String[]{"1481495165907509250", "1481495305896599553"},true);

                AScoreNum aScoreNum = new AScoreNum().setName(ascore.getBpname())
                        .setSelf(selfSubmitSum + "/" + selfSum)
                        .setDiff(diffSubmitSum + "/" + diffSum)
                        .setLeader(leaderSubmitSum + "/" + leaderSum)
                        .setService(serviceSubmitSum + "/" + serviceSum);
                aScoreNums.add(aScoreNum);
            }
        });
        return aScoreNums;
    }

    @Override
    public List<ABCDNum> getABCDNumlist(String pname) {
        List<ABCDNum> abcdNums = new ArrayList<>();
        // 获取列表
        QueryWrapper<Ascore> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("Distinct bpid, bpname");
        List<Ascore> list = this.list(queryWrapper);
        list.forEach(ascore -> {
            if (pname.equals("") || ascore.getBpname().equals(pname)){
                // 获取每一项自评的总人数
                Integer selfASum = getABCDSum(ascore.getBpid(), new String[]{"1477556092805337089", "1477561398275952642"}, "100");
                Integer selfBSum = getABCDSum(ascore.getBpid(), new String[]{"1477556092805337089", "1477561398275952642"}, "89");
                Integer selfCSum = getABCDSum(ascore.getBpid(), new String[]{"1477556092805337089", "1477561398275952642"}, "79");
                Integer selfDSum = getABCDSum(ascore.getBpid(), new String[]{"1477556092805337089", "1477561398275952642"}, "59");

                Integer diffASum = getABCDSum(ascore.getBpid(), new String[]{"1477561726815784961", "1477561857279610881"}, "100");
                Integer diffBSum = getABCDSum(ascore.getBpid(), new String[]{"1477561726815784961", "1477561857279610881"}, "89");
                Integer diffCSum = getABCDSum(ascore.getBpid(), new String[]{"1477561726815784961", "1477561857279610881"}, "79");
                Integer diffDSum = getABCDSum(ascore.getBpid(), new String[]{"1477561726815784961", "1477561857279610881"}, "59");

                Integer serviceASum = getABCDSum(ascore.getBpid(), new String[]{"1477562158057345026", "1477562403365408770", "1477562805473333249", "1477562999044657153"}, "100");
                Integer serviceBSum = getABCDSum(ascore.getBpid(), new String[]{"1477562158057345026", "1477562403365408770", "1477562805473333249", "1477562999044657153"}, "89");
                Integer serviceCSum = getABCDSum(ascore.getBpid(), new String[]{"1477562158057345026", "1477562403365408770", "1477562805473333249", "1477562999044657153"}, "79");
                Integer serviceDSum = getABCDSum(ascore.getBpid(), new String[]{"1477562158057345026", "1477562403365408770", "1477562805473333249", "1477562999044657153"}, "59");

                Integer leaderASum = getABCDSum(ascore.getBpid(), new String[]{"1481495165907509250", "1481495305896599553"}, "100");
                Integer leaderBSum = getABCDSum(ascore.getBpid(), new String[]{"1481495165907509250", "1481495305896599553"}, "89");
                Integer leaderCSum = getABCDSum(ascore.getBpid(), new String[]{"1481495165907509250", "1481495305896599553"}, "79");
                Integer leaderDSum = getABCDSum(ascore.getBpid(), new String[]{"1481495165907509250", "1481495305896599553"}, "59");


                ABCDNum abcdNum = new ABCDNum().setName(ascore.getBpname())
                        .setSelfA(String.valueOf(selfASum))
                        .setSelfB(String.valueOf(selfBSum))
                        .setSelfC(String.valueOf(selfCSum))
                        .setSelfD(String.valueOf(selfDSum))
                        .setDiffA(String.valueOf(diffASum))
                        .setDiffB(String.valueOf(diffBSum))
                        .setDiffC(String.valueOf(diffCSum))
                        .setDiffD(String.valueOf(diffDSum))
                        .setServiceA(String.valueOf(serviceASum))
                        .setServiceB(String.valueOf(serviceBSum))
                        .setServiceC(String.valueOf(serviceCSum))
                        .setServiceD(String.valueOf(serviceDSum))
                        .setLeaderA(String.valueOf(leaderASum))
                        .setLeaderB(String.valueOf(leaderBSum))
                        .setLeaderC(String.valueOf(leaderCSum))
                        .setLeaderD(String.valueOf(leaderDSum));
                abcdNums.add(abcdNum);
            }
        });
        return abcdNums;
    }

    @Override
    public List<NoScoreVo> getNoScoreList(String item) {

        List<NoScoreVo> noScoreVos = new ArrayList<>();

        QueryWrapper<Ascore> ascoreQueryWrapper = new QueryWrapper<>();
        ascoreQueryWrapper.eq("status", "未打分");
        List<Ascore> list = this.list(ascoreQueryWrapper);
        Set<String> strings = new HashSet<>();

        list.forEach(ascore -> {
            strings.add(ascore.getApid());
        });

        QueryWrapper<Apeo> apeoQueryWrapper = new QueryWrapper<>();
        apeoQueryWrapper.in("id",strings);
        apeoQueryWrapper.orderByDesc("drole");
        apeoQueryWrapper.orderByAsc("dsit");
        apeoQueryWrapper.orderByAsc("rsit");
        if (item != null) {
            JSONObject jsonObject = JSON.parseObject(item);
            if (!isEmpty(jsonObject.get("dname"))) {
                apeoQueryWrapper.like("dname", jsonObject.get("dname"));
            }
        }
        List<Apeo> apeos = apeoMapper.selectList(apeoQueryWrapper);
        apeos.forEach(apeo -> {
            NoScoreVo noScoreVo = new NoScoreVo().setDname(apeo.getDname()).setPname(apeo.getName());
            noScoreVos.add(noScoreVo);
        });
        return noScoreVos;
    }


    @Override
    public boolean updateScore(Ascore item) {
        this.updateById(item);
        if (!item.getStatus().equals(SUBMIT)){ return true; }

        // 提交时
        QueryWrapper<Ascore> ascoreQueryWrapper = new QueryWrapper<>();
        ascoreQueryWrapper.eq("bpid",item.getBpid());
        ascoreQueryWrapper.eq("itid",item.getItid());
        ascoreQueryWrapper.eq("aid",item.getAid());
        ascoreQueryWrapper.eq("status",SUBMIT);
        List<Ascore> list = this.list(ascoreQueryWrapper);
        final double[] aDouble = {(double) 0};
        final int[] num = {0};
        list.forEach(ascore -> {
            num[0] = num[0] + 1;
            double v = "无".equals(ascore.getScore()) ? 0.0 : Double.parseDouble(ascore.getScore());
            aDouble[0] = aDouble[0] +  v;
        });
        double avg = num[0] != 0?(aDouble[0] / num[0]):0;

        QueryWrapper<Aitemavg> aitemavgQueryWrapper = new QueryWrapper<>();
        aitemavgQueryWrapper.eq("aid",item.getAid());
        aitemavgQueryWrapper.eq("itid",item.getItid());
        aitemavgQueryWrapper.eq("pid",item.getBpid());
        List<Aitemavg> aitemavgs = aitemavgMapper.selectList(aitemavgQueryWrapper);
        aitemavgMapper.updateById(aitemavgs.get(0).setScore(avg+""));
        return true;
    }

    @Override
    public boolean updateScoreBatch(List<Ascore> item) {
        this.updateBatchById(item);
        if (!item.get(0).getStatus().equals(SUBMIT)){ return true; }

        DecimalFormat df = new DecimalFormat("#.00");
        // 计算被评人的平均分
        QueryWrapper<Ascore> ascoreQueryWrapper = new QueryWrapper<>();
        ascoreQueryWrapper.select("DISTINCT itid");
        ascoreQueryWrapper.eq("aid",item.get(0).getAid());
        ascoreQueryWrapper.eq("status",SUBMIT);

        // 获取所有的打分项
        List<Ascore> list = this.list(ascoreQueryWrapper);
        list.forEach(itid->{
        // Ascore itid = list.get(2);
        log1.info("当前打分项:{}", itid);
            // 计算每个部门每个评分项多少分
            QueryWrapper<Ascore> queryWrapper = new QueryWrapper<>();
            // queryWrapper.select("DISTINCT bpid");
            queryWrapper.eq("itid",itid.getItid());
            queryWrapper.eq("aid",item.get(0).getAid());
            queryWrapper.eq("status",SUBMIT);
            queryWrapper.ne("score","无");
            queryWrapper.orderByAsc("bpid");
            List<Ascore> list2 = this.list(queryWrapper);
            // 统计所有分数求平均值
            String combpname = "";
            final double[] aDouble = {(double) 0};
            final int[] num = {0};
            for (int i = 0; i < list2.size(); i++) {
                Ascore ascore = list2.get(i);
                if (i == 0){ combpname = ascore.getBpname(); }
                log1.info("combpname={}", combpname);
                log1.info("总分={}", aDouble[0]);
                log1.info("数量={}", num[0]);
                log1.info("打分信息{}-{}-{}-{}",ascore.getItname(), ascore.getBpname(),ascore.getApname(), ascore.getScore());
                if(!combpname.equals(ascore.getBpname())){
                    // 下一个了
                    combpname = ascore.getBpname();
                    double avg =  num[0] != 0?(aDouble[0] / num[0]):0;
                    log1.info("当前总分={}", aDouble[0]);
                    log1.info("当前数量={}", num[0]);
                    log1.info("平均分{}", avg);
                    QueryWrapper<Aitemavg> aitemavgQueryWrapper = new QueryWrapper<>();
                    aitemavgQueryWrapper.eq("aid", ascore.getAid());
                    aitemavgQueryWrapper.eq("itid", ascore.getItid());
                    aitemavgQueryWrapper.eq("pid", ascore.getBpid());
                    List<Aitemavg> aitemavgs = aitemavgMapper.selectList(aitemavgQueryWrapper);
                    log1.info("更新信息{}", aitemavgs.get(0).setScore(df.format(avg)));
                    aitemavgMapper.updateById(aitemavgs.get(0).setScore(df.format(avg)));
                    num[0] = 0;
                    aDouble[0] = 0;

                }
                num[0] = num[0] + 1;
                double v = "无".equals(ascore.getScore()) ? 0.0 : Double.parseDouble(ascore.getScore());
                aDouble[0] = aDouble[0] +  v;
            }
        });
        return true;
    }

}
